
const PORT = 8000;
const { Pool } = require('pg');
const pool = new Pool({
    user: 'postgres',
    host: 'project_data_base',
    //host: '127.0.0.1',
    database: 'postgres',
    password: '1234',
    port: 5432,
  });
  const { v4: uuidv4 } = require('uuid');

function generateUniqueCode() {
  const uniqueId = BigInt('0x' + uuidv4().replace(/-/g, '')).toString();
    const uniqueCode = uniqueId.substring(0, 10);
  return uniqueCode;
}

// Пример использования функции
const uniqueCode = generateUniqueCode();
console.log("Уникальный код:", uniqueCode);

  /**
 * @swagger
 * components:
 *   schemas:
 *     Population:
 *       type: object
 *       properties:
 *         pid:
 *           type: integer
 *         pname:
 *           type: string
 *         startdate:
 *           type: string
 *           format: date
 */
class populations {
    /**
     * @swagger
     * /population:
     *   get:
     *     tags: [Популяции]
     *     summary: Получение списка популяций
     *     parameters:
     *       - in: query
     *         name: limit
     *         schema:
     *           type: integer
     *         description: Лимит записей для возврата
     *       - in: query
     *         name: offset
     *         schema:
     *           type: integer
     *         description: Смещение для пагинации
     *     responses:
     *       200:
     *         description: Список популяций
     *         content:
     *           application/json:
     *             schema:
     *               type: object
     *               properties:
     *                 populations:
     *                   type: array
     *                   items:
     *                     $ref: '#/components/schemas/Population'
     *                 next:
     *                   type: string
     *                   nullable: true
     *                 previous:
     *                   type: string
     *                   nullable: true
     *       500:
     *         description: Внутренняя ошибка сервера
     */
    async populationGet (req, res) {
          try {
            const limit = req.query.limit || 10;
            const offset = req.query.offset || 0;
            const active = req.query.active;
        
            let queryText = `
              SELECT * FROM population as p join equipment as e on p.equipment_id=e.eid
            `;
            if(active){
              queryText = `
              SELECT * FROM population as p join equipment as e on p.equipment_id=e.eid where p.active=true
            `;
            }
            const values = [limit, offset];
        
            const result = await pool.query(queryText);
            const populations = result.rows;
        
            const nextOffset = populations.length < limit ? 0 : parseInt(offset) + parseInt(limit);
            const previousOffset = parseInt(offset) - parseInt(limit) >= 0 ? parseInt(offset) - parseInt(limit) : null;
        
            const response = {
                populations,
                next: nextOffset === 0 ? null : `http://localhost:${PORT}/population?limit=${limit}&offset=${nextOffset}`,
                previous: previousOffset === null? null : `http://localhost:${PORT}/population?limit=${limit}&offset=${previousOffset}`,
            };
        
            res.json(response);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
        async populationCode (req, res) {
          try {
        
            const queryText = `
              SELECT pid FROM population order by pid desc limit 1 
            `;
            const result = await pool.query(queryText);
            const code = generateUniqueCode();
        
            const response = {
                code,
            };
        
            res.json(response);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
    /**
     * @swagger
     * /population:
     *   post:
     *     tags: [Популяции]
     *     summary: Создание новой популяции
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             properties:
     *               pname:
     *                 type: string
     *               startdate:
     *                 type: string
     *                 format: date
     *     responses:
     *       200:
     *         description: Новая популяция создана
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/Population'
     *       500:
     *         description: Внутренняя ошибка сервера
     */  

  async populationPost(req, res) {
    try {
      const {
        pcode,
        pname,
        startdate,
        avg_start_mass,
        avg_start_size,
        start_count,
        equipment_id,
        comment
      } = req.body;

      const queryText = `
        INSERT INTO population (
          pcode,
          pname,
          startdate,
          avg_start_mass,
          avg_start_size,
          start_count,
          equipment_id,
          comment
        )
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
        RETURNING *;
      `;

      const values = [pcode, pname, startdate, avg_start_mass, avg_start_size, start_count, equipment_id, comment];

      const result = await pool.query(queryText, values);
      const newPopulation = result.rows[0];

      const queryEq = `
      UPDATE equipment
      SET free = false
      WHERE eid = $1
      RETURNING *;
      `;
      const eqVal = [equipment_id]
      const eqresult = await pool.query(queryEq, eqVal);

      res.json(newPopulation);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }

  async populationPoolPost(req, res) {
    try {
      const {
        pid,
        eid,
        equipment_id
      } = req.body;

      const queryEq1 = `
      UPDATE equipment
      SET free = true
      WHERE eid = $1
      RETURNING *;
      `;
      const eqVal1 = [eid]
      const eqresult1 = await pool.query(queryEq1, eqVal1);
      console.log(eqresult1)
      const queryText = `
        UPDATE population 
        SET equipment_id = $1
        WHERE pid = $2
        RETURNING *;
      `;

      const values = [equipment_id, pid];

      const result = await pool.query(queryText, values);
      const newPopulation = result.rows[0];

      const queryEq = `
      UPDATE equipment
      SET free = false
      WHERE eid = $1
      RETURNING *;
      `;
      const eqVal = [equipment_id]
      const eqresult = await pool.query(queryEq, eqVal);

      let poolQ = `
      UPDATE logs
      SET date_time_end = $1
      WHERE population_id = $2 AND date_time_end IS NULL
      RETURNING *;
      `;
      let poolVal = [new Date(), pid]
      let poolResult = await pool.query(poolQ, poolVal);
      console.log(poolResult)
      poolQ = `
      INSERT INTO logs (
        population_id,
        pools,
        date_time_start
        )
        VALUES ($1, $2, $3)
      RETURNING *;
      `;
      poolVal = [pid, equipment_id ,new Date()]
      poolResult = await pool.query(poolQ, poolVal);

      res.json(newPopulation);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }
  
}

module.exports = new populations()
